const config_module = require("./config")
const const_module = require("./const")
const grpc = require('@grpc/grpc-js')
const message_proto = require("./proto")
const {v4: uuidv4} = require('uuid')
const email_module = require('./email')
const redis_module = require('./redis')

async function GetVarifyCode(call, callback) {
    console.log("email is ", call.request.email)
    try{
        // 查询邮箱是否在redis是否存在
        let query_res = await redis_module.GetRedis(config_module.code_prefix+call.request.email);
        let uniqueId = query_res;
        if(query_res == null){
            // 说明不存在 创建uuid
            uniqueId = uuidv4();
            if(uniqueId == null){
                console.log("uniqueId is empty");
                return ;
            }
            if(uniqueId.length > 6){
                uniqueId = uniqueId.slice(-6).toUpperCase();
            }
            
            // 存储到redis中
            let bres = await redis_module.SetRedisExpire(
                const_module.code_prefix+call.request.email,uniqueId,
                config_module.varifySafeTime);
            if(!bres){
                console.log("setRedis is error");
                callback(null,{
                    email: call.request.email,
                    error: const_module.Errors.RedisErr
                });
                return ;
            }
        }
        console.log("uniqueId is ", uniqueId);
        let text_str =  '尊敬的用户，您的注册验证码为：'+uniqueId+'，有效期为三分钟，请勿泄露于他人！'
        console.log("准备发送消息")
        //发送邮件
        let mailOptions = {
            from: config_module.email_user,
            to: call.request.email,
            subject: '验证码',
            text: text_str,
        };
        console.log("mailOptions is ", mailOptions)
        // 等待邮件发送
        //let send_res = await email_module.SendMail(mailOptions);
        send_res = true;
        console.log("send res is ", send_res)

        if(!send_res){
            callback(null, {
                email:  call.request.email,
                error:const_module.Errors.RedisErr
            }); 
            return ;
        }else{
            callback(null, {
                email:  call.request.email,
                error:const_module.Errors.Success
            }); 
        }



    }catch(error){
        console.log("catch error is ", error)

        callback(null, { email:  call.request.email,
            error:const_module.Errors.Exception
        }); 
    }

}

function main() {
    var server = new grpc.Server()
    var urlPort = config_module.myServer_url + ':' + config_module.myServer_port;
    console.log(urlPort)    
    server.addService(message_proto.VarifyService.service, { GetVarifyCode: GetVarifyCode })
    server.bindAsync(urlPort, grpc.ServerCredentials.createInsecure(), () => {
        server.start()
        console.log('grpc server started')        
    })
}

main()